<template>
	<el-form :rules="rules" ref="loginForm" :model="loginForm" class="loginContainer">
		<h3 class="loginTitle">系统登录</h3>
		<el-form-item prop="username">
			<el-input type="text" v-model="loginForm.username" placeholder="请输入用户名"></el-input>
		</el-form-item>
		<el-form-item prop="password">
			<el-input type="password" v-model="loginForm.password" placeholder="请输入密码"></el-input>
		</el-form-item>
		<el-form-item prop="verifyCode">
			<el-row type="flex" >
				<el-col :span="11">
					<el-input type="text" v-model="loginForm.verifyCode"  
						placeholder="请输入验证码"/>
				</el-col>
				<el-col :span="7" >
					<kaptcha ref="kap" v-if="activateK"></kaptcha>
				</el-col>
			</el-row>
		</el-form-item>

		<el-button type="primary" style="width: 100%;" @click="login">登录</el-button>
	</el-form>
</template>

<script>
	import {
		mapActions
	} from 'pinia';
	import {
		useLoginStore
	} from "../store";
	import kaptcha from "@/components/Kaptcha.vue"
	import {
		ElForm,
		ElMessage,
		ElButton
	} from 'element-plus'
	export default {
		components: {
			kaptcha
		},
		data() {
			return {
				loading: false,
				activateK:true,
				loginForm: {
					username: "",
					password: "",
					verifyCode: ""
				},
				rules: {
					username: [{
						required: true,
						message: '请输入用户名',
						trigger: 'blur'
					}],
					password: [{
						required: true,
						message: '请输入密码',
						trigger: 'blur'
					}]
				}
			}
		},
		methods: {
			...mapActions(useLoginStore, ["userLogin"]),
			async login() {
				try {
					await this.$refs.loginForm.validate();
					const formData = new FormData();
					formData.append("username", this.loginForm.username);
					formData.append("password", this.loginForm.password);
					formData.append("verifyCode", this.loginForm.verifyCode);
					formData.append("uuid", this.$refs.kap.uuid);
					let result = await this.$axios.post("/login", formData);
					let {
						code,
						msg,
						data
					} = result.data;
					console.log(result.data)
					if (code == 0) {
						//从响应头获取token
						let token = result.headers["authorization"]
						this.userLogin(data, token);
						let redictUrl = this.$route.query.redirect;
						if (redictUrl == undefined) this.$router.push("/");
						else this.$router.push(redictUrl);
					} else {
						ElMessageBox.alert(msg, "提示");
						this.activateK=false;
						this.$nextTick(()=>{
							this.activateK=true;
						})						
					}
				} catch (e) {
					console.log(e)
				}
			}
		}
	}
</script>

<style>
	.loginContainer {
		border-radius: 15px;
		background-clip: padding-box;
		margin: 180px auto;
		width: 350px;
		padding: 15px 35px 15px 35px;
		background: #fff;
		border: 1px solid #eaeaea;
		box-shadow: 0 0 25px #cac6c6;
	}

	.loginTitle {
		margin: 15px auto 20px auto;
		text-align: center;
		color: #505458;
	}

	.el-form-item__content {
		display: flex;
		align-items: center;
	}
</style>